package top.atcra.rpc.serialization.impl;

import lombok.extern.slf4j.Slf4j;
import top.atcra.rpc.exception.SerializeException;
import top.atcra.rpc.serialization.Serializer;

import java.io.*;

/**
 * 使用Java的ObjectInputStream和ObjectOutputStream序列化/反序列化对象
 *
 * @author atcra
 * @date 2025-3-23
 */
@Slf4j
public class JavaObjectSerializer implements Serializer {

    @Override
    public byte[] serialize(Object obj) {
        if (obj == null) {
            return null;
        }
        try (
                ByteArrayOutputStream bais = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(bais)
        ) {
            objectOutputStream.writeObject(obj);
            byte[] result = bais.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("使用jdk方式序列化对象【{}】成功，编码后二进制长度为{}", obj, result.length);
            }
            return result;
        } catch (IOException e) {
            log.error("使用jdk方式序列化对象【{}】出现异常", obj, e);
        }
        return null;
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }

        try (
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream objectInputStream = new ObjectInputStream(bais)
        ) {
            Object object = objectInputStream.readObject();

            if (log.isDebugEnabled()) {
                log.debug("使用jdk方式反序列化对象【{}】成功", clazz);
            }

            return (T) object;
        } catch (IOException | ClassNotFoundException e) {
            log.error("使用jdk方式反序列化对象【{}】出现异常", clazz, e);
            throw new SerializeException(e);
        }
    }
}
